import {Component, OnInit, ViewChild} from "@angular/core";
import "datatables";
import {ModalDirective} from "ng2-bootstrap/ng2-bootstrap";
import {UserinfoModifyApprService} from "./userinfo-modify.service";
import {ApprInfo} from "./appr-info.class";
import {FormBuilder} from "@angular/forms";
import {DataTablesComponent, DataTablesComponentConfig} from "app/theme/components/dataTables";
import {SearchForm} from "./search-form.class";
import {UIModAppr} from "./uiMod-appr.class";

@Component({
  selector: 'userinfo-modify-approval',
  templateUrl: 'userinfo-modify.component.html',
  styleUrls: ['userinfo-modify.component.scss'],
  providers: [UserinfoModifyApprService]
})
export class UserinfoModifyApprComponent implements OnInit {
  @ViewChild('apprPassModal') apprPassModal: ModalDirective;
  @ViewChild('apprRejectModal') apprRejectModal: ModalDirective;
  @ViewChild('apprReviewModal') apprReviewModal: ModalDirective;
  @ViewChild('apprDeleteModal') apprDeleteModal: ModalDirective;
  @ViewChild('apprTimeModal') apprTimeModal: ModalDirective;
  @ViewChild(DataTablesComponent) dataTable: DataTablesComponent;

  private apprInfo: ApprInfo = new ApprInfo();
  private _selectdAppr: UIModAppr;
  private originDetailData: UIModAppr;
  private searchForm: SearchForm = new SearchForm();

  private apprUrl = '/water/userInfoSub/auditInfoModify';
  private apprInfoUrl = '/water/userInfoSub/view';
  private apprOrigInfoUrl = '/water/userInfoSub/getOrInfoForAdmin';
  private apprTableUrl = '/water/userInfoSub/getAllchangedPerson';
  private apprDownloadUrl = '/water/userInfoSub/printModInfoTab';
  private apprDeleteUrl = '/water/userInfoSub/delete';
  private downloadIdUrl = '/water/usersub/printSummaryTableByIdsOFM';
  private downloadTimeUrl = '/water/usersub/printSummaryTableByStageOFM';

  private downloadUrlByPoint = '';
  private downloadUrlByStage = '';

  private disableReviewBtn = true;
  private disablePassBtn = true;
  private disableRejectBtn = true;
  private disableDownloadBtn = true;
  private disableDeleteBtn = true;
  private disableDownloadTimeBtn: boolean = false;

  private selectedRowData: any[];
  private _errorMsg: string;
  private errorShow = false;

  private dataTablesConfig: DataTablesComponentConfig = new DataTablesComponentConfig();

  public loading = false;

  constructor(private _fb: FormBuilder, private _service: UserinfoModifyApprService) {
  }

  ngOnInit() {
    this.initDatatables();
  }

  search() {
    this.dataTable.draw();
  }

  private initDatatables() {
    this.dataTablesConfig.ajaxUrl = this.apprTableUrl;
    this.dataTablesConfig.columnsDef = [
      {'name': '姓名', 'id': 'name'},
      {'name': '身份证', 'id': 'idcard'},
      {'name': '新地址', 'id': 'address'},
      {'name': '新政治面貌', 'id': 'government'},
      {'name': '新联系方式', 'id': 'telephone'},
      {'name': '提交时间', 'id': 'submittime', 'orderable': true},
      {'name': '审批时间', 'id': 'verifytime', 'orderable': true},
      {'name': '状态', 'id': 'verified'}
    ];
  }

  tableRowSelect(rowData: any[]) {
    this.disableAllButtons();
    if (rowData.length > 0) {
      this.disableReviewBtn = rowData.length !== 1;
      this.disableDownloadBtn = rowData.length == 0 || rowData[0].verified !== '通过';
      if (!this.disableDownloadBtn) {
        this.downloadUrlByPoint = this.downloadIdUrl + '?pkid=' + rowData[0].pkid;
        for (let i = 1; i < rowData.length; i++) {
          let data = rowData[i];
          this.downloadUrlByPoint = this.downloadUrlByPoint + ',' + data.pkid;
        }
        this.downloadUrlByPoint += '&type=个人信息变更';
      }
      this.disablePassBtn = this.disableRejectBtn = rowData[0].verified !== '待审核';
      this.disableDeleteBtn = rowData.length == 0 || rowData[0].verified == '待审核';

      this.selectedRowData = rowData;
    }
  }

  handleError(e:any){
    if(e.type == 'error'){
     this.errorShow = true;
    }
  }

  private disableAllButtons() {
    this.disableReviewBtn = this.disablePassBtn = this.disableRejectBtn = this.disableDownloadBtn = this.disableDeleteBtn = true;
  }

  review() {
    let pkid = this.selectedRowData[0].pkid;

    this.getUserOriginInfo(pkid);
    this.loadInfo(pkid);
  }

  private loadInfo(pkid: string) {
    this._selectdAppr = new UIModAppr();
    this._service.reviewAppr(this.apprInfoUrl, pkid)
      .then(res => {
        if (res.status === 'success') {
          this._selectdAppr = res.data;
          this.apprReviewModal.show();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  private getUserOriginInfo(pkid: string) {
    this.originDetailData = new UIModAppr();
    this._service.getUserOriginInfo(this.apprOrigInfoUrl, pkid)
      .then(res => {
        if (res.status === 'success') {
          this.originDetailData = res.data;
          this.apprReviewModal.show();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });

  }

  showPassModal() {
    this.apprPassModal.show();
  }

  showRejectModal() {
    this.apprRejectModal.show();
  }

  showDeleteModal() {
    this.apprDeleteModal.show();
  }

  showTimeModal() {
    this.apprTimeModal.show();
  }


  onHideModal(): void {
    jQuery('.modal-backdrop').remove();
  }

  updateDateRange(event) {
    this.searchForm.startdate = this.date2String(event.beginDate);
    this.searchForm.enddate = this.date2String(event.endDate);
  }

  getStage(event) {
    const startdate = this.date2String(event.beginDate);
    const enddate = this.date2String(event.endDate);
    this.downloadUrlByStage = this.downloadTimeUrl + '?startdate=' + startdate + '&enddate=' + enddate + '&type=个人信息变更';
  }

  private date2String(date: any): string {
    if (Object.keys(date).length === 0 || date === null || date === undefined || (date.year == 0 && date.month == 0 && date.day == 0)) {
      return null;
    }

    let str = date.year + '-';
    if (date.month < 10) {
      str += '0';
    }
    str += date.month + '-';

    if (date.day < 10) {
      str += '0';
    }
    str += date.day;
    return str;
  }

  public pass(comment: string): void {
    this._saveAppr(comment, 'pass', this.apprPassModal);
  }

  public reject(comment: string): void {
    this._saveAppr(comment, 'reject', this.apprRejectModal);
  }

  public apprRejectClose() {
    this._errorMsg = null;
    this.apprRejectModal.hide();
  }

  public apprPassClose() {
    this._errorMsg = null;
    this.apprPassModal.hide();
  }

  public apprDeleteClose() {
    this._errorMsg = null;
    this.apprDeleteModal.hide();
  }

  public apprTimeClose() {
    this._errorMsg = null;
    this.apprTimeModal.hide();
  }


  public delete(): void {
    let pkids = [];
    for (let row of this.selectedRowData) {
      pkids.push(row.pkid);
    }
    this._service.deleteAppr(this.apprDeleteUrl, pkids)
      .then(res => {
        if (res.status === 'success') {
          this.apprDeleteModal.hide();
          this.dataTable.draw(false);
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }


  private _saveAppr(comment, apprStatus, modal: ModalDirective) {
    this.loading = true;

    let ids = [];
    for (let row of this.selectedRowData) {
      ids.push(row.ids);
    }
    this.apprInfo.ids = ids;

    this.apprInfo.verifydescription = comment;
    this.apprInfo.flag = apprStatus;
    this._service.submitAppr(this.apprUrl, this.apprInfo).then(result => {
      if (result.status === 'success') {
        modal.hide();
        this.apprReviewModal.hide();
        this.dataTable.draw(false);
      } else {
        this._errorMsg = result.data;
      }

      this.loading = false;
    }, error => {
      this._errorMsg = error;
    });
  }
}
